package com.jh.paymentchannel.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jh.paymentchannel.pojo.BankInfoCode;
import com.jh.paymentchannel.pojo.BankNumCode;
import com.jh.paymentchannel.pojo.JFMQuickBindCard;
import com.jh.paymentchannel.pojo.JFQuickRegister;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Objects;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.PayGetToken;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.TokenConstants;

import cn.jh.common.tools.Log;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class JFMQuickPageRequest {

	private static final Logger LOG = LoggerFactory.getLogger(JFMQuickPageRequest.class);

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;

//	// 服务商编号
//	@Value("${jfm.org_no}")
//	private String partnerNo;
//
//	@Value("${jfm.url}")
//	private String JFMurl;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	private String Key = "00000000000000000000000000000000";
	
	private String partnerNo = "TEST001";
	
	private String JFMurl = "http://fast.jfpays.com:19087";
	
	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	private String rateCode = "1000005";

	private String capAmount = "999999";

	// 进件接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglvquick/register")
	public @ResponseBody Object jfshanglvRegister(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName) throws Exception {
		LOG.info("=========开始进入进件接口=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		// 获取用户的userid
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfm");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		// userid
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费用
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		// 获取用户的商户id
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		String shopUserId;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject = JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			LOG.error("查询用户ID出错！！！！");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有查询到用户ID");
			return maps;
		}
		LOG.info("随机获取的userId" + shopUserId);

		// 获取用户的商户全称
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}

		// 商户名称
		String merName = resultObj.getString("name");

		// 获取默认结算卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			LOG.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String bankAccountNo = resultObj.getString("cardNo");
		// 用户名
		String bankAccountName = resultObj.getString("userName");
		// 身份证号
		String idCardNo = resultObj.getString("idcard");
		// 预留手机号
		String phoneno = resultObj.getString("phone");
		// 银行名
		String bankName = resultObj.getString("bankName");
		
		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		}else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		// 查询银行卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("接口/v1.0/user/bank/default/cardno=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			LOG.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		String str = jsonObject.getString("result");
		if (str.equals(null) || "null".equals(str)) {
			map.put("resp_code", "failed");
			map.put("resp_message", "查询银行卡信息为null");
			return map;
		}
		// 支行联行号
		String bankChannelNo = null;
		try {
			BankInfoCode bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankBranchName);
			bankChannelNo = bankInfoCodeByBankName.getBankNo();
		} catch (Exception e) {
			LOG.info("支行联行号查询有误=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_tag", "jf");
			map.put("resp_message", "查询支行联行号有误！");
			return map;
		}
		String cardName = resultObj.getString("bankName");
		String cardname = Util.queryBankNameByBranchName(cardName);
		String expiredTime = resultObj.getString("expiredTime");
		String securityCode = resultObj.getString("securityCode");
		String cardtype = resultObj.getString("cardType");
		
		BankNumCode bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
		// 英文代号
		String bankCode = bankNumCodeByBankName.getBankCode();
		// 银行代码
		String bankAbbr = bankNumCodeByBankName.getBankNum();

		// 进件接口的交易代码
		String txnCode = "701001";
		String api = "/rest/api/" + txnCode;

		// 生成一个8位随机数
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String merchantCode = uuid.substring(0, 8);
		LOG.info("merchantCode=========" + merchantCode);
		
		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.MERCHANT_REGISTERED_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}
		String extrafee = "";
		Double valueOf = Double.valueOf(extraFee);
		if(valueOf!=0 && valueOf>2){
			extrafee = new BigDecimal(valueOf.toString()).multiply(new BigDecimal("100")).setScale(0).toString();
		}else{
			extrafee = "200";
		}
		capAmount = new BigDecimal(Double.valueOf(capAmount).toString()).multiply(new BigDecimal("100")).setScale(0).toString();
		
		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// 令牌
		dto.put("merchantCode", merchantCode);// 商户号
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("merName", merName);// 商户名称
		dto.put("merAbbr", merName);// 商户简称
		dto.put("idCardNo", idCardNo);// 身份证号
		dto.put("bankAccountNo", bankAccountNo);// 银行卡号
		dto.put("phoneno", phoneno);// 银行预留手机号
		dto.put("bankAccountName", bankAccountName);// 持卡人姓名
		dto.put("bankAccountType", "PRIVATE");// 银行账户类型
		dto.put("bankName", bankName);// 银行名称
		dto.put("bankSubName", bankBranchName);// 支行名称
		dto.put("bankCode", bankCode);// 英文代号
		dto.put("bankAbbr", bankAbbr);// 银行代码
		dto.put("bankChannelNo", bankChannelNo);// 支行联行号
		dto.put("bankProvince", provinceOfBank);// 开户行省份
		dto.put("bankCity", cityOfBank);// 开户行城市
		dto.put("debitRate", rate);// 借记卡费率
		dto.put("debitCapAmount", capAmount);// 借记卡封顶
		dto.put("creditRate", rate);// 信用卡费率
		dto.put("creditCapAmount", capAmount);// 信用卡封顶
		dto.put("withdrawDepositRate", "0.0001");// 提现费率
		dto.put("withdrawDepositSingleFee", extrafee);// 单笔提现手续费
		dto.put("isOrgMerchant", "N");// 是否机构商户
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));

		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			LOG.info("head=======" + head);
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，进件失败啦！");
			return map;
		}
		if("000000".equals(respCode) && "success".equals(respMsg)){
			// 进件成功返回的商户号
			String merchantUuid = jsonObject.getString("merchantUuid");
			//进件成功返回的Uuid
			String paltMerchantCode = jsonObject.getString("paltMerchantCode");
			LOG.info("merchantUuid======" + merchantUuid);
			LOG.info("paltMerchantCode======" + paltMerchantCode);
			
        	JFQuickRegister jfregister = topupPayChannelBusiness.getJFQuickRegisterByBankCard(bankCard);
        	String fee = Double.valueOf(extrafee)/100+"";
        	if(jfregister == null){
        		LOG.info("=========保存用户进件开始=========");
        		JFQuickRegister jfQuickRegister = new JFQuickRegister();
        		jfQuickRegister.setPhone(phoneno);
    			jfQuickRegister.setBankCard(bankCard);
    			jfQuickRegister.setIdCard(idCardNo);
    			jfQuickRegister.setMerchantUuid(merchantUuid);
    			jfQuickRegister.setMerchantCode(paltMerchantCode);
    			jfQuickRegister.setRateCode2(rateCode);
    			jfQuickRegister.setDebitRate(rate);
    			jfQuickRegister.setWithdrawDepositsingleFee(extraFee);
    			jfQuickRegister.setProvince(provinceOfBank);
    			jfQuickRegister.setCity(cityOfBank);
    			jfQuickRegister.setBankbranchname(bankBranchName);
        		try {
        			topupPayChannelBusiness.createJFQuickRegister(jfQuickRegister);
        			LOG.info("==========保存语句执行了=========");
				} catch (Exception e) {
					map.put("resp_code", "failed");	
			        map.put("channel_type", "jf");
					map.put("resp_message", "进件信息保存失败");
					return map;
				}
        		
        		restTemplate = new RestTemplate();
    			uri = util.getServiceUrl("user", "error url request!");
    			url = uri.toString() + "/v1.0/user/bank/update/bynewcardno";
    			requestEntity = new LinkedMultiValueMap<String, String>();
    			requestEntity.add("cardNo", bankAccountNo);
    			requestEntity.add("province", provinceOfBank);
    			requestEntity.add("city", cityOfBank);
    			requestEntity.add("bankBranchName", bankBranchName);
    			result = restTemplate.postForObject(url, requestEntity, String.class);
    			LOG.info("=========RESULT=========" + result);
    			try {
    				jsonObject = JSONObject.fromObject(result);
    				resultObj = jsonObject.getJSONObject("result");
    			} catch (Exception e) {
    				LOG.error("更新银行信息出错");
    				maps.put("resp_code", "failed");
    				maps.put("channel_type", "jf");
    				maps.put("resp_message", "更新银行信息有误");
    				return maps;
    			}
    			LOG.info("=========进件成功=========" + res);
    			LOG.info("=========开始绑卡=========");
    			map.put("resp_code", "success");
    			map.put("channel_type", "jf");
    			map.put("redirect_url",
    					ipAddress + "/v1.0/paymentchannel/topup/tojfshanglvbindcard?bankName="
    							+ URLEncoder.encode(cardname, "UTF-8") + "&cardType=" + URLEncoder.encode(cardtype, "UTF-8")
    							+ "&bankCard=" + bankCard + "&ordercode=" + ordercode + "&expiredTime=" + expiredTime
    							+ "&securityCode=" + securityCode);
    			return map;
        	} else {
    			LOG.info("=========进件失败了=========" + respMsg);
    			map.put("resp_code", "failed");
    			map.put("channel_type", "jf");
    			map.put("resp_message", respMsg);
    			return map;
    		}
		}
		return null;
	}

	// 商户侧绑卡接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/backopencard")
	public @ResponseBody Object jfShangLvBackOpenCard(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "expiredTime", required = false) String expiredTime,
			@RequestParam(value = "securityCode", required = false) String securityCode) throws Exception {
		LOG.info("=========开始进入商户侧绑卡接口=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		//充值金额
		String amount = resultObj.getString("amount");
		//userid
		String userid = resultObj.getString("userid");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		// 末端商户号
		String platMerchantCode = jfQuickRegister.getMerchantCode();
		String cardname = Util.queryBankNameByBranchName(bankName);
		
		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		}else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		// 根据银行名称获取银行编码
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bankcode/getcodebyname";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("name", bankName);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
		} catch (Exception e) {
			LOG.error("根据银行名称获取银行编码失败");
			maps.put("resp_code", "failed");
			maps.put("resp_message", "根据银行名称获取银行编码失败");
			return maps;
		}
		// 银行编号
		String code = jsonObject.getString("result");
		
		BankNumCode  bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
		// 英文代号
		String bankCode = bankNumCodeByBankName.getBankCode();
		// 银行代码
		String bankAbbr = bankNumCodeByBankName.getBankNum();

		String returnUrl = ipAddress + "/v1.0/paymentchannel/topup/jfshanglv/return_call";
		String notifyUrl = ipAddress + "/v1.0/paymentchannel/topup/jfshanglv/notify_call";
		
		String before = expiredTime.substring(0, 2);
		String after = expiredTime.substring(2, 4);

		BigDecimal big = new BigDecimal(before);
		BigDecimal times = new BigDecimal("12");

		int compareTo = big.compareTo(times);
		// 如果前两位大于12，,代表是年/月的格式
		if (compareTo == 1) {
			expiredTime = before + after;
		} else {
			expiredTime = after + before;
		}
		
		// 商户侧绑卡接口的交易代码
		String txnCode = "701003";
		String api = "/rest/api/" + txnCode;

		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.OPEN_CARD_BACK_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}
		
		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// 令牌
		dto.put("smsOrderId", ordercode);// 短信订单号
		dto.put("platMerchantCode", platMerchantCode);// 末端商户号
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("accountName", userName);// 银行卡户名
		dto.put("cardNo", cardNo);// 银行卡卡号
		dto.put("cardType", "C");// 银行卡类型
		dto.put("certType", "ID");// 证件类型
		dto.put("certNo", idcard);// 身份证号
		dto.put("phoneno", phone);// 银行预留手机号
		dto.put("cvn2", securityCode);// cvn2
		dto.put("expired", expiredTime);// 有效期
		dto.put("pageReturnUrl", returnUrl);// 前台通知地址
		dto.put("offlineNotifyUrl", notifyUrl);// 后台通知地址
		dto.put("bankCode", bankCode);// 英文代号
		dto.put("bankAbbr", bankAbbr);// 银行代码
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));

		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode = null;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			LOG.info("head=======" + head);
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
			return map;
		}
		if ("000000".equals(respCode) && "success".equals(respMsg)) {
			LOG.info("=========绑卡成功了=========");
			JFMQuickBindCard jfmQuickBindCard = new JFMQuickBindCard();
			jfmQuickBindCard.setUserId(Long.parseLong(userid));
			jfmQuickBindCard.setBankCard(bankCard);
			jfmQuickBindCard.setIdCard(idcard);
			jfmQuickBindCard.setPhone(phone);
			jfmQuickBindCard.setCreateTime(new Date());
			try {
				topupPayChannelBusiness.createJFMQuickBindCard(jfmQuickBindCard);
			} catch (Exception e) {
				LOG.info("=========绑卡失败了=========" + respMsg);
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
				map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfmbindcarderror");
				return map;
			}
			LOG.info("=========绑卡成功=========" + respMsg);
			LOG.info("=========第一次支付=========");
			
			restTemplate = new RestTemplate();
			uri = util.getServiceUrl("user", "error url request!");
			url = uri.toString() + "/v1.0/user/bank/default/userid";
			requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("user_id", userid);
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("=========RESULT=========" + result);
			try {
				jsonObject = JSONObject.fromObject(result);
				resultObj = jsonObject.getJSONObject("result");
			} catch (Exception e) {
				LOG.error("查询默认结算卡出错");
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询默认结算卡有误");
				return map;
			}
			if (resultObj.isNullObject()) {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "没有结算卡");
				return map;
			}
			//开户行所在省
			String provinceOfBank = resultObj.getString("province");
			System.out.println("provinceOfBank" + provinceOfBank);
			//开户行所在市
			String cityOfBank = resultObj.getString("city");
			System.out.println("cityOfBank" + cityOfBank);
			//支行名称
			String bankBranchName = resultObj.getString("bankBranchName");
			String cardType = resultObj.getString("cardType");
			// 支行联行号
			String bankBranchNo = null;
			try {
				BankInfoCode bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankBranchName);
				bankBranchNo = bankInfoCodeByBankName.getBankNo();
			} catch (Exception e) {
				LOG.info("支行联行号查询有误=========" + e);
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "查询支行联行号有误");
				return map;
			}
			System.out.println("bankBranchNo" + bankBranchNo);
			
			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/tojfshanglvbankinfo"+"?bankName="+URLEncoder.encode(bankName,"UTF-8")+"&bankBranchId="+bankBranchNo+
					"&bankNo="+cardNo+"&bankCard="+bankCard+"&cardName="+URLEncoder.encode(cardname,"UTF-8")+"&amount="+amount+"&ordercode="+ordercode+
					"&provinceOfBank="+URLEncoder.encode(provinceOfBank,"UTF-8")+"&cityOfBank="+URLEncoder.encode(cityOfBank,"UTF-8")+
					"&bankBranchName="+URLEncoder.encode(bankBranchName,"UTF-8")+"&cardType="+URLEncoder.encode(cardType,"UTF-8")+"&isRegister=2");
			return map;
			
		} else if ("init".equals(respMsg) || "signing".equals(respMsg)) {
			Map status = jfShangLvOpenCardQuery(request,ordercode);
			respCode = (String) status.get("resp_code");
			respMsg = (String) status.get("resp_message");
			LOG.info("=========resp_code=========" + respCode);
			LOG.info("=========resp_message=========" + respMsg);
		} else if ("fail".equals(respMsg) || "invalid".equals(respMsg)) {
			LOG.info("=========绑卡失败了=========" + respMsg);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
			map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfmbindcarderror");
			return map;
		}
		return null;
	}

	// 支付短信接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/consumesms")
	public @ResponseBody Object jfShangLvConsumeSMS(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {
		LOG.info("=========跳转成功并进入支付短信接口=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		// 金额
		String amount = resultObj.getString("amount");
		amount = new BigDecimal(Double.valueOf(amount).toString()).multiply(new BigDecimal("100")).setScale(0).toString();
		// 用户userid
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 用户总额外费用
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String platMerchantCode = jfQuickRegister.getMerchantCode();

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		}else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}
		
		BankNumCode  bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
		// 英文代号
		String bankCode = bankNumCodeByBankName.getBankCode();
		// 银行代码
		String bankAbbr = bankNumCodeByBankName.getBankNum();

		// 支付短信接口的交易代码
		String txnCode = "702003";
		String api = "/rest/api/" + txnCode;

		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.PAY_SMS_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}
		
		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// 令牌
		dto.put("consumeOrderId", ordercode);// 订单号
		dto.put("platMerchantCode", platMerchantCode);// 凭条商户号
		dto.put("merchantRateCode", rateCode);// 商户费率编号
		dto.put("payAmount", amount);// 支付金额
		dto.put("accountName", userName);// 银行卡户名
		dto.put("cardNo", cardNo);// 银行卡卡号
		dto.put("cardType", "C");// 银行卡类型
		dto.put("certType", "ID");// 证件类型
		dto.put("certNo", idcard);// 身份证号
		dto.put("phoneno", phone);// 银行预留手机号
		dto.put("bankCode", bankCode);// 英文代号
		dto.put("bankAbbr", bankAbbr);// 银行代码
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));

		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode = null;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			LOG.info("head=======" + head);
			String payNo = jsonObject.getString("payNo");
			LOG.info("payNo=======" + payNo);
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
			if ("000000".equals(respCode) && "success".equals(respMsg)) {
				LOG.info("=========消费短信发送成功了=========");
				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("resp_message", payNo);
			} else {
				LOG.info("=========消费短信发送失败了=========" + respMsg);
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
			}
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
		}
		return map;
	}
	
	// 支付接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/consume")
	public @ResponseBody Object jfShangLvConsume(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "smsCode") String smsCode) throws Exception {
		LOG.info("=========开始进入消费支付接口=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		// 金额
		String amount = resultObj.getString("amount");
		amount = new BigDecimal(Double.valueOf(amount).toString()).multiply(new BigDecimal("100")).setScale(0).toString();
		// 用户userid
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 用户总额外费用
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String platMerchantCode = jfQuickRegister.getMerchantCode();

		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		}else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}

		// 根据银行名称获取银行编码
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bankcode/getcodebyname";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("name", bankName);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
		} catch (Exception e) {
			LOG.error("根据银行名称获取银行编码失败");
			maps.put("resp_code", "failed");
			maps.put("resp_message", "根据银行名称获取银行编码失败");
			return maps;
		}
		// 银行编号
		String code = jsonObject.getString("result");

		BankNumCode bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
		// 英文代号
		String bankCode = bankNumCodeByBankName.getBankCode();
		// 银行代码
		String bankAbbr = bankNumCodeByBankName.getBankNum();

		// 异步通知地址
		String notifyUrl = ipAddress + "/v1.0/paymentchannel/topup/jfmshanglv/pay_notify_call";
		
		// 消费支付接口的交易代码
		String txnCode = "702001";
		String api = "/rest/api/" + txnCode;

		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.CONSUME_PAY_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}

		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// 令牌
		dto.put("consumeOrderId", ordercode);// 支付订单号
		dto.put("platMerchantCode", platMerchantCode);// 凭条商户号
		dto.put("smsCode", smsCode);// 短信验证码
		dto.put("merchantRateCode", rateCode);// 商户费率编号
		dto.put("payAmount", amount);// 支付金额
		dto.put("accountName", userName);// 银行卡户名
		dto.put("cardNo", cardNo);// 银行卡卡号
		dto.put("cardType", "C");// 银行卡类型
		dto.put("certType", "ID");// 证件类型
		dto.put("certNo", idcard);// 身份证号
		dto.put("phoneno", phone);// 银行预留手机号
		dto.put("bankCode", bankCode);// 英文代号
		dto.put("bankAbbr", bankAbbr);// 银行代码
		dto.put("productName", "卧槽王尼玛");// 商品名称
		dto.put("productDesc", "这是王尼玛的描述");// 商品描述
		dto.put("callBackUrl", notifyUrl);// 回调地址
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));

		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode = null;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			LOG.info("head=======" + head);
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfmpayerror");
		}
		if ("000000".equals(respCode) && "success".equals(respMsg)) {
			LOG.info("=========支付成功了=========");
			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfmpaysuccess");
		} else {
			LOG.info("=========支付失败了=========" + respMsg);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfmpayerror");
		}
		return map;
	}

	// 提现接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/withdraw")
	public @ResponseBody Object Withdraw(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {
		LOG.info("=========开始进入提现接口=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		//实际金额
		String realamount = resultObj.getString("realAmount");
		//userid
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");
		//总金额
		String amount = resultObj.getString("amount");
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {
			maps.put("resp_code", "failed");
			maps.put("channel_type", "jf");
			maps.put("resp_message", "没有结算卡");
			return maps;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		//用户名
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		//银行预留手机号
		String phone = resultObj.getString("phone");
		//银行名称
		String bankName = resultObj.getString("bankName");
		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		} else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/query/randomuserid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		String shopUserId = null;
		try {
			result = restTemplate.postForObject(url, requestEntity, String.class);
			jsonObject = JSONObject.fromObject(result);
			shopUserId = jsonObject.getString("result");
		} catch (Exception e1) {
			LOG.error("查询用户ID出错！！！！");
			maps.put("resp_code", "failed");
			maps.put("channel_type", "sdj");
			maps.put("resp_message", "没有查询到用户ID");
			return maps;
		}
		LOG.info("随机获取的userId" + shopUserId);

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/shops/query/uid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("userid", shopUserId);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询商铺信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfcoin");
			map.put("resp_message", "查询商铺信息有误");
			return map;
		}
		String shopName = resultObj.getString("name");// 商户全称

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("接口/v1.0/user/bank/default/cardno=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			LOG.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		String str = jsonObject.getString("result");
		if (str.equals(null) || "null".equals(str)) {
			map.put("resp_code", "failed");
			map.put("resp_message", "查询银行卡信息为null");
			return map;
		}
		String cardName = resultObj.getString("bankName");
		String cardname = Util.queryBankNameByBranchName(cardName);
		
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String province = jfQuickRegister.getProvince();
		String city = jfQuickRegister.getCity();
		String bankbranchname = jfQuickRegister.getBankbranchname();
		String merchantCode = jfQuickRegister.getMerchantCode();
		String merchantUuid = jfQuickRegister.getMerchantUuid();

		// 将额外费用变成以分为单位
		String ExtraFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();

		BankNumCode  bankNumCodeByBankName;
		// 英文代号
		String bankCode = null;
		// 银行代码
		String bankAbbr = null;
		try {
			bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
			bankCode = bankNumCodeByBankName.getBankCode();
			bankAbbr = bankNumCodeByBankName.getBankNum();
		} catch (Exception e) {
			LOG.info("获取银行代码代号出错啦=======" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取银行代码代号出错啦");
			return map;
		}

		// 支行联行号
		String bankChannelNo = null;
		try {
			BankInfoCode bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankbranchname);
			bankChannelNo = bankInfoCodeByBankName.getBankNo();
		} catch (Exception e) {
			LOG.info("支行联行号查询有误=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_tag", "jf");
			map.put("resp_message", "查询支行联行号有误！");
			return map;
		}

		BigDecimal bigamount = new BigDecimal(amount);
		BigDecimal bigrate = new BigDecimal(rate);
		BigDecimal bigextraFee = new BigDecimal(extraFee);

		// 订单总金额乘以费率的值
		BigDecimal multiply = bigamount.multiply(bigrate);
		// 订单总金额减去 订单总金额乘以费率的值
		BigDecimal subtract = bigamount.subtract(multiply);
		// 再减去额外费用
		BigDecimal Amount = subtract.subtract(bigextraFee);

		BigDecimal setScale = Amount.setScale(2, RoundingMode.CEILING);

		String SetScale = new BigDecimal(setScale + "").multiply(new BigDecimal("100")).setScale(0).toString();
		
		// 提现接口的交易代码
		String txnCode = "702002";
		String api = "/rest/api/" + txnCode;
		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.PAY_AMOUNT_WITHDRAW_DEPOSIT_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}
		LOG.info("用户提现的金额=====SetScale");
		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// token
		dto.put("merchantUuid", merchantUuid);// 商户UUID
		dto.put("withdrawOrderId", ordercode);// 提现订单号
		dto.put("walletType", "400");// 钱包类型
		dto.put("amount", SetScale);// 提现金额
		dto.put("bankAccountName", userName);// 银行卡户名
		dto.put("bankAccountNo", cardNo);// 银行卡卡号
		dto.put("bankAccountType", "PRIVATE");// 银行账户类型
		dto.put("bankName", bankName);// 银行名称
		dto.put("bankSubName", bankbranchname);// 支行名称
		dto.put("bankChannelNo", bankChannelNo);// 支行联行号
		dto.put("bankCode", bankCode);// 银行代码
		dto.put("bankAbbr", bankAbbr);// 银行代号
		dto.put("bankProvince", province);// 银行省份
		dto.put("bankCity", city);// 银行城市
		dto.put("bankArea", city);// 银行区县
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));
		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode = null;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
			if ("000000".equals(respCode) && "success".equals(respMsg)) {
				map.put("resp_code", "success");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
			} else {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", respMsg);
			}
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
		}
		return null;
	}
	
	// 结算卡变更接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/updatecard")
	public @ResponseBody Object jfShangLvUpdateCard(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode,
			@RequestParam(value = "provinceOfBank") String provinceOfBank,
			@RequestParam(value = "cityOfBank") String cityOfBank,
			@RequestParam(value = "bankBranchName") String bankBranchName) throws Exception {
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");
		//userid
		String userid = resultObj.getString("userid");
		//费率
		String rate = resultObj.getString("rate");
		// 额外费用
		String extraFee = resultObj.getString("extraFee");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		// 查询银行卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("接口/v1.0/user/bank/default/cardno=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			LOG.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		String str = jsonObject.getString("result");
		if (str.equals(null) || "null".equals(str)) {
			map.put("resp_code", "failed");
			map.put("resp_message", "查询银行卡信息为null");
			return map;
		}
		// 支行联行号
		String bankChannelNo = null;
		try {
			BankInfoCode bankInfoCodeByBankName = topupPayChannelBusiness.getBankInfoCodeByBankName(bankBranchName);
			bankChannelNo = bankInfoCodeByBankName.getBankNo();
		} catch (Exception e) {
			LOG.info("支行联行号查询有误=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_tag", "jf");
			map.put("resp_message", "查询支行联行号有误！");
			return map;
		}
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		jsonObject = JSONObject.fromObject(result);
		resultObj = jsonObject.getJSONObject("result");
		// 银行卡号
		String cardNo = resultObj.getString("cardNo");
		// 用户名
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		// 手机号
		String phone = resultObj.getString("phone");
		System.out.println("provinceOfBank" + provinceOfBank);
		System.out.println("cityOfBank" + cityOfBank);
		// 银行名称
		String bankName = resultObj.getString("bankName");
		
		if (bankName.contains("邮")) {
			bankName = "中国邮政储蓄银行";
		}else if (bankName.contains("浦")) {
			bankName = "上海浦东发展银行";
		}
		
		// 银行卡类型
		String cardType = resultObj.getString("cardType");
		// 通过 userId 查询用户进件信息
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String platMerchantCode = jfQuickRegister.getMerchantCode();

		BankNumCode bankNumCodeByBankName = topupPayChannelBusiness.getBankNumCodeByBankName(bankName);
		// 英文代号
		String bankCode = bankNumCodeByBankName.getBankCode();
		// 银行代码
		String bankAbbr = bankNumCodeByBankName.getBankNum();

		String extrafee = "";
		Double valueOf = Double.valueOf(extraFee);
		if(valueOf!=0 && valueOf>2){
			extrafee = new BigDecimal(valueOf.toString()).multiply(new BigDecimal("100")).setScale(0).toString();
		}else{
			extrafee = "200";
		}
		capAmount = new BigDecimal(Double.valueOf(capAmount).toString()).multiply(new BigDecimal("100")).setScale(0).toString();
		
		
		// 结算卡变更接口的交易代码
		String txnCode = "701004";
		String api = "/rest/api/" + txnCode;

		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.MERCHANT_CHANGE_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}

		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// 令牌
		dto.put("platMerchantCode", platMerchantCode);// 平台商户号
		dto.put("changeType", "2");// 变更类型
		dto.put("bankAccountNo", cardNo);// 银行卡卡号(结算卡)
		dto.put("phoneno", phone);// 银行卡预留手机号
		dto.put("bankName", bankName);// 银行名称
		dto.put("bankSubName", bankBranchName);// 银行支行名称
		dto.put("bankCode", bankCode);// 英文代号
		dto.put("bankAbbr", bankAbbr);// 银行代码
		dto.put("bankChannelNo", bankChannelNo);// 支行联行号
		dto.put("bankProvince", provinceOfBank);// 开户行省份
		dto.put("bankCity", cityOfBank);// 开户行城市
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("debitRate", rate);// 借记卡费率
		dto.put("debitCapAmount", capAmount);// 借记卡封顶
		dto.put("creditRate", rate);// 信用卡费率
		dto.put("creditCapAmount", capAmount);// 信用卡封顶
		dto.put("withdrawDepositRate", "0.0001");// 提现费率
		dto.put("withdrawDepositSingleFee", extrafee);// 单笔提现手续费
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));

		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode = null;
		String respMsg = null;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			LOG.info("head=======" + head);
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
			return map;
		}
		if ("000000".equals(respCode) && "success".equals(respMsg)) {
			JFQuickRegister jfQuickRegisterByIdCard = topupPayChannelBusiness.getJFQuickRegisterByIdCard(idcard);
			jfQuickRegisterByIdCard.setBankCard(cardNo);
			topupPayChannelBusiness.createJFQuickRegister(jfQuickRegisterByIdCard);
			LOG.info("=========结算卡变更成功了=========");
			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url",ipAddress + "/v1.0/paymentchannel/topup/jfshanglvpay?ordercode="+ordercode);
			return map;
		}else {
			LOG.info("=========结算卡变更失败了=========" + respMsg);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", respMsg);
			return map;
		}
	}

	// 用于绑卡请求跳转的接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/turntobindcardpage")
	public @ResponseBody Object jfShangLvTurnToPage(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {
		LOG.info("=========开始进入绑卡请求跳转接口=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		// 用户userid
		String userid = resultObj.getString("userid");
		// 充值卡卡号
		String bankCard = resultObj.getString("bankcard");

		// 查询信用卡信息
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("接口/v1.0/user/bank/default/cardno=========RESULT=========" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			LOG.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}
		String str = jsonObject.getString("result");
		if (str.equals(null) || "null".equals(str)) {
			map.put("resp_code", "failed");
			map.put("resp_message", "查询银行卡信息为null");
			return map;
		}
		// 银行名
		String cardName = resultObj.getString("bankName");
		// 有效期
		String expiredTime = resultObj.getString("expiredTime");
		// 安全码
		String securityCode = resultObj.getString("securityCode");
		// 银行卡类型
		String cardtype = resultObj.getString("cardType");
		
		String cardname = Util.queryBankNameByBranchName(cardName);

		map.put("resp_code", "success");
		map.put("channel_type", "jf");
		map.put("redirect_url",
				ipAddress + "/v1.0/paymentchannel/topup/tojfshanglvbindcard?bankName="
						+ URLEncoder.encode(cardname, "UTF-8") + "&cardType=" + URLEncoder.encode(cardtype, "UTF-8")
						+ "&bankCard=" + bankCard + "&ordercode=" + ordercode + "&expiredTime=" + expiredTime
						+ "&securityCode=" + securityCode);
		return map;
	}

	//用于跳转支付请求的接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/turntojfshanglvpaypage")
	public @ResponseBody Object jfShangLvTurnToPayPage(HttpServletRequest request,
			@RequestParam(value = "ordercode") String ordercode) throws Exception {
		Map map = new HashMap();
		
		map.put("resp_code", "success");
		map.put("channel_type", "jf");
		map.put("redirect_url", ipAddress + "/v1.0/paymentchannel/topup/jfshanglvpay?&ordercode=" + ordercode);
		
		return map;
	}
	
	//用户进入支付请求的接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfshanglvpay")
	public String returnjfShangLvpay(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		LOG.info("=========开始进入支付请求跳转接口=========");
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String ordercode = request.getParameter("ordercode");
		model.addAttribute("ordercode", ordercode);
		
		return "jfshanglvpaymessage";
	}

	// 跳转确认提现卡页面的中转接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tojfshanglvbankinfo")
	public String tojfshanglvbankinfo(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		LOG.info("/v1.0/paymentchannel/topup/tojfshanglvbankinfo=========tojfshanglvbankinfo");
		
		String bankName = request.getParameter("bankName");// 结算卡银行名称
		String bankNo = request.getParameter("bankNo");// 结算卡卡号
		String amount = request.getParameter("amount");
		String ordercode = request.getParameter("ordercode");
		String provinceOfBank = request.getParameter("provinceOfBank");
		String cityOfBank = request.getParameter("cityOfBank");
		String bankBranchName = request.getParameter("bankBranchName");
		String bankBranchId = request.getParameter("bankBranchId");
		String cardType = request.getParameter("cardType");// 结算卡的卡类型
		String isRegister = request.getParameter("isRegister");
		String cardtype = request.getParameter("cardtype");// 信用卡的卡类型
		String bankCard = request.getParameter("bankCard");// 充值卡卡号
		String cardName = request.getParameter("cardName");// 充值卡银行名称
		String expiredTime = request.getParameter("expiredTime");// 充值卡银行名称
		String securityCode = request.getParameter("securityCode");// 充值卡银行名称

		model.addAttribute("bankName", bankName);
		model.addAttribute("bankNo", bankNo);
		model.addAttribute("amount", amount);
		model.addAttribute("ordercode", ordercode);
		model.addAttribute("provinceOfBank", provinceOfBank);
		model.addAttribute("cityOfBank", cityOfBank);
		model.addAttribute("bankBranchName", bankBranchName);
		model.addAttribute("bankBranchId", bankBranchId);
		model.addAttribute("cardType", cardType);
		model.addAttribute("isRegister", isRegister);
		model.addAttribute("cardtype", cardtype);
		model.addAttribute("bankCard", bankCard);
		model.addAttribute("cardName", cardName);
		model.addAttribute("expiredTime", expiredTime);
		model.addAttribute("securityCode", securityCode);
		
		return "jfshanglvbankInfo";
	}

	// 跳转确认绑信用卡页面的中转接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/tojfshanglvbindcard")
	public String tojfshanglvbindcard(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		LOG.info("/v1.0/paymentchannel/topup/tojfshanglvbindcard=========tojfshanglvbindcard");
		String cardname = request.getParameter("bankName");// 信用卡银行名称
		String ordercode = request.getParameter("ordercode");// 订单号
		String cardType = request.getParameter("cardType");// 卡类型
		String bankCard = request.getParameter("bankCard");// 充值卡卡号
		String expiredTime = request.getParameter("expiredTime");// 有效期
		String securityCode = request.getParameter("securityCode");// 安全码

		model.addAttribute("bankName", cardname);
		model.addAttribute("ordercode", ordercode);
		model.addAttribute("cardType", cardType);
		model.addAttribute("bankCard", bankCard);
		model.addAttribute("expiredTime", expiredTime);
		model.addAttribute("securityCode", securityCode);
		return "jfshanglvbindcard";
	}
	
	// 银行卡开通状态查询
	public Map jfShangLvOpenCardQuery(HttpServletRequest request, String ordercode) throws Exception {
		LOG.info("=========开始进入银行卡开通状态查询=========");
		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		LOG.info("=========RESULT=========" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e1) {
			LOG.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		String userid = resultObj.getString("userid");
		// 通过 userId 查询用户进件信息
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		// 身份证号
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		String bankName = resultObj.getString("bankName");
		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		// 末端商户号
		String platMerchantCode = jfQuickRegister.getMerchantCode();

		// 卡开通状态查询的交易代码
		String txnCode = "701010";
		String api = "/rest/api/" + txnCode;

		PayGetToken payGetToken = new PayGetToken();
		String tokenText = null;
		try {
			tokenText = payGetToken.token(Key, TokenConstants.OPEN_CARD_STATUS_QUERY_TOKEN, ordercode, partnerNo, JFMurl);
		} catch (Exception e) {
			LOG.info("=========RESULT=========" + e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "获取token错误");
			return map;
		}

		JSONObject dto = new JSONObject();
		dto.put("token", tokenText);// 令牌
		dto.put("smsOrderId", ordercode);// 短信订单号
		dto.put("platMerchantCode", platMerchantCode);// 末端商户号
		dto.put("head", payGetToken.getHead(ordercode, partnerNo, txnCode));

		String execute = payGetToken.execute(Key, JFMurl, api, dto.toString(), partnerNo, ordercode);
		LOG.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			jsonObject = JSONObject.fromObject(res);
			LOG.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			LOG.info("head=======" + head);
			respCode = head.getString("respCode");
			LOG.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			LOG.info("respMsg======" + respMsg);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，卡开通状态查询失败！");
			return map;
		}
		map.put("resp_code", respCode);
		map.put("channel_type", "jf");
		map.put("resp_message", respMsg);
		return map;
	}
	
	// 请求支付接口成功跳转页面接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfmpaysuccess")
	public String returnjfmpaysuccess(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		return "sdjsuccess";
	}

	// 请求支付接口失败跳转页面接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfmpayerror")
	public String returnjfmpayerror(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		return "sdjerror";
	}

	// 绑卡成功同步通知跳转页面接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfmbindcardsuccess")
	public String returnjfmbindcardsuccess(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		return "cjbindcardsuccess";
	}

	// 绑卡失败同步通知跳转页面接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfmbindcarderror")
	public String returncjbindcarderror(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		return "cjbindcarderror";
	}
	
	// 商户绑卡同步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/return_call")
	public String cjReturnCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map map = new HashMap();
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		LOG.info("=========商户绑卡同步通知进来了=========");
		
		return "cjbindcardsuccess";
	}

	// 商户绑卡异步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfshanglv/notify_call")
	public void jfshangaoNotifyCallback(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String encryptData, @RequestParam String signature) throws Exception {
		LOG.info("=========商户绑卡异步通知进来了=========");
		String dataPlain = AES.decode(Base64.decode(encryptData), Key.substring(0, 16));
		LOG.info("=========消费回调：dataPlain: {} =========", dataPlain);
		String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));
		LOG.info("=========消费回调：checkSign: {} =========", checkSign);
		if (!Objects.equal(signature, checkSign)) {
			LOG.error("=========签名验证失败=========");
		}
		com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		LOG.info("=========parseObject=========" + parseObject);
		com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		LOG.info("=========jsonObject2=========" + jsonObject2);
		String respCode = jsonObject2.getString("respCode");
		LOG.info("=========respCode=========" + respCode);
		String respMsg = jsonObject2.getString("respMsg");
		LOG.info("=========respMsg=========" + respMsg);
		String orderId = jsonObject2.getString("orderId");
		LOG.info("=========orderId=========" + orderId);

		if ("000000".equals(respCode)) {
			String activateStatus = parseObject.getString("activateStatus");
			LOG.info("=========activateStatus=========" + activateStatus);
			if ("SUCCESS".equalsIgnoreCase(activateStatus)) {
				Map map = new HashMap();
				Map<String, String> maps = new HashMap<String, String>();
				RestTemplate restTemplate = new RestTemplate();
				URI uri = util.getServiceUrl("transactionclear", "error url request!");
				String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
				MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("order_code", orderId);
				String result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("=========RESULT=========" + result);
				JSONObject jsonObject = JSONObject.fromObject(result);
				JSONObject resultObj = jsonObject.getJSONObject("result");
				String userid = resultObj.getString("userid");
				// 充值卡卡号
				String bankCard = resultObj.getString("bankcard");
				String phone = resultObj.getString("phone");

				// 查询信用卡信息
				restTemplate = new RestTemplate();
				uri = util.getServiceUrl("user", "error url request!");
				url = uri.toString() + "/v1.0/user/bank/default/cardno";
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("cardno", bankCard);
				requestEntity.add("type", "0");
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("接口/v1.0/user/bank/default/cardno=========RESULT=========" + result);
				try {
					jsonObject = JSONObject.fromObject(result);
					resultObj = jsonObject.getJSONObject("result");
				} catch (Exception e) {
					LOG.error("=========查询银行卡信息出错=========");
				}
				String userName1 = resultObj.getString("userName");
				// 身份证号 
				String idcard1 = resultObj.getString("idcard");
				String phone1 = resultObj.getString("phone");
				String bankName1 = resultObj.getString("bankName");
				JFMQuickBindCard jfmBindCard = topupPayChannelBusiness.getJFMQuickBindCard(Long.parseLong(userid), bankCard);
				if (null == jfmBindCard) {
					JFMQuickBindCard jfmBindCard1 = new JFMQuickBindCard();
					jfmBindCard1.setPhone(phone1);
					jfmBindCard1.setIdCard(idcard1);
					jfmBindCard1.setBankCard(bankCard);
					try {
						topupPayChannelBusiness.createJFMQuickBindCard(jfmBindCard1);
					} catch (Exception e) {
						LOG.error(e.getMessage());
					}
				} else {
					jfmBindCard.setPhone(phone1);
					jfmBindCard.setIdCard(idcard1);
					jfmBindCard.setBankCard(bankCard);
					try {
						topupPayChannelBusiness.createJFMQuickBindCard(jfmBindCard);
					} catch (Exception e) {
						LOG.error(e.getMessage());
					}
				}
				LOG.info("=========用户绑卡成功并存入数据库=========");
				PrintWriter writer = response.getWriter();
				writer.print("000000");
				writer.close();
			}
		}
	}
	
	// 支付接口异步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfmshanglv/pay_notify_call")
	public void paynotifyCall(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String encryptData, @RequestParam String signature) throws Exception {
		LOG.info("异步回调进来了");
		String dataPlain = AES.decode(Base64.decode(encryptData), Key.substring(0, 16));
		LOG.info("消费回调：dataPlain: {} ", dataPlain);
		String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));
		LOG.info("消费回调：checkSign: {} ", checkSign);
		if (!Objects.equal(signature, checkSign)) {
			LOG.error("签名验证失败");
		}
		com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		LOG.info("parseObject===========" + parseObject);
		com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		String workId = jsonObject2.getString("workId");
		LOG.info("workId======" + workId);
		String respCode = jsonObject2.getString("respCode");
		LOG.info("respCode======" + respCode);
		String respMsg = jsonObject2.getString("respMsg");
		LOG.info("respMsg======" + respMsg);
		String orderId = jsonObject2.getString("orderId");
		LOG.info("orderId======" + orderId);
		try {
			Log.setLogFlag(true);
			Log.println("=========交易： 订单结果异步通知=========");
			LOG.info("=========交易： 订单结果异步通知=========");
			if ("success".equals(respMsg) && "000000".equals(respCode)) { // 订单已支付;
				// 1、检查Amount和商户系统的订单金额是否一致
				// 2、订单支付成功的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理）；
				// 3、返回响应内容
				synchronized (this) {
					// **更新订单状态*//*
					// **调用下单，需要得到用户的订单信息*//*
					RestTemplate restTemplate = new RestTemplate();
					URI uri = util.getServiceUrl("transactionclear", "error url request!");
					String url = uri.toString() + "/v1.0/transactionclear/payment/update";
					// **根据的用户手机号码查询用户的基本信息*//*
					MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
					requestEntity.add("status", "1");
					requestEntity.add("third_code", workId);
					requestEntity.add("order_code", orderId);
					String result = restTemplate.postForObject(url, requestEntity, String.class);
					LOG.info("=========订单状态修改成功=========");
					LOG.info("订单已支付!");
					response.getWriter().write("000000");
				}
			} else {
				// 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
				// 2、返回响应内容
				LOG.info("订单支付失败!");
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		LOG.info("=========处理完成=========");
	}

}
